import { defineStore } from "pinia";
import { ref } from "vue";
import type { User } from "@/types";
import { STORAGE_KEYS } from "@/config";
import { setItem, getItem, removeItem, isTokenValid } from "@/utils/storage";
import {
  login as loginApi,
  register as registerApi,
  logout as logoutApi,
} from "@/api/auth";
import {
  getUserInfo as getUserInfoApi,
  updateUserInfo as updateUserInfoApi,
} from "@/api/user";
import router from "@/router";

export const useUserStore = defineStore("user", () => {
  // 状态
  const storedToken = getItem(STORAGE_KEYS.TOKEN);
  const token = ref<string>(
    storedToken && isTokenValid(storedToken) ? storedToken : ""
  );
  const userInfo = ref<User | null>(
    token.value ? getItem(STORAGE_KEYS.USER_INFO) : null
  );
  const loading = ref(false);

  // 检查token是否有效
  const checkTokenValidity = () => {
    if (token.value && !isTokenValid(token.value)) {
      logout();
      router.push("/login");
    }
  };

  // 登录
  const login = async (data: { username: string; password: string }) => {
    loading.value = true;
    try {
      const response = await loginApi({
        account: data.username,
        password: data.password,
      });
      if (response.code === 200 && response.data) {
        token.value = response.data.token;
        userInfo.value = {
          id: response.data.userId,
          username: response.data.username,
          nickname: response.data.nickname,
          avatar: response.data.avatar,
          status: 1,
          email: response.data.email,
        };

        setItem(STORAGE_KEYS.TOKEN, response.data.token);
        setItem(STORAGE_KEYS.USER_INFO, userInfo.value);
      }
      return response;
    } finally {
      loading.value = false;
    }
  };

  // 注册
  const register = async (data: {
    username: string;
    password: string;
    email: string;
    nickname: string;
  }) => {
    loading.value = true;
    try {
      const response = await registerApi(data);
      return response;
    } finally {
      loading.value = false;
    }
  };

  // 获取用户信息
  const getUserInfo = async () => {
    if (!token.value) return null;

    try {
      const response = await getUserInfoApi();
      if (response.code === 200 && response.data) {
        userInfo.value = response.data;
        setItem(STORAGE_KEYS.USER_INFO, response.data);
      }
      return response;
    } catch (error) {
      logout();
      return null;
    }
  };

  // 登出
  const logout = async () => {
    try {
      await logoutApi();
    } finally {
      // 无论后端请求是否成功，都清除本地状态
      token.value = "";
      userInfo.value = null;
      removeItem(STORAGE_KEYS.TOKEN);
      removeItem(STORAGE_KEYS.USER_INFO);
    }
  };

  // 更新用户信息
  const updateUserInfo = async (data: Partial<User>) => {
    const response = await updateUserInfoApi(data);
    if (response.code === 200 && response.data) {
      userInfo.value = response.data;
      setItem(STORAGE_KEYS.USER_INFO, response.data);
    }
    return response;
  };

  return {
    token,
    userInfo,
    loading,
    login,
    register,
    getUserInfo,
    logout,
    updateUserInfo,
    checkTokenValidity,
  };
});
